package com.element.oauth2.server.handler;

import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.oauth2.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthErrorAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException e) throws IOException {
        VoidResult result = VoidResult.failed(SecurityErrorCode.A_ACCESS_DENIED);
        if (e instanceof OAuth2AuthorizationCodeRequestAuthenticationException) {
            logger.error("OAuth2AuthorizationCodeRequestAuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), e);
            String errorCode = ((OAuth2AuthorizationCodeRequestAuthenticationException) e).getError().getErrorCode();
            if ("invalid_request".equals(errorCode)) {
                result = VoidResult.failed(SecurityErrorCode.A_INVALID_REQUEST);
            }
        } else if (e instanceof BadCredentialsException) {
            logger.error("BadCredentialsException异常,请求路径:{},异常信息:", request.getServletPath(), e);
            BadCredentialsException exception = (BadCredentialsException) e;
            result = VoidResult.failed(SecurityErrorCode.A_USERNAME_OR_PASSWORD_ERROR.getErrNum(), exception.getMessage());
        } else {
            logger.error("AuthErrorAuthenticationFailureHandler异常,请求路径:{},异常信息:", request.getServletPath(), e);
        }
        ResponseUtil.writeJson(response, result);
    }
}